<?php

/**
 *
 * BEGIN StatsAdmin.php
 *
 *
 * @file StatsAdmin.php
 * @brief This class provides data access methods to generate game statistics
 * @author Thato Selebogo, Wits University
 * @copyright Â© Wits University 2011 - All Rights Reserved
 * @license BSD License (http://www.linfo.org/bsdlicense.html)
 * @date 21 October 2011
 *
 *
 * BEGIN CHANGELOG
 * Developers working on thee files are REQUIRED to maintain this CHANGELOG.
 * Please ensure you follow the Changelog Guidelines: http://code.google.com/p/dazzler/wiki/DazzlerDevelopGuideline?ts=1315476570&updated=DazzlerDevelopGuideline
 * !==================================================================================================================================================================
 *
 * VERSION 1.0.0
 * 	+ File Created, Thato Selebogo, 21 September 2011
 *
 *
 * ================================================================================================================================================================!
 * END CHANGELOG
 */
/* * *****************************************************************************************************************************************************************
 *
 * BEGIN Direct Call Check
 *
  /***************************************************************************************************************************************************************** */
class StatsAdmin extends baseClass {

    /**
     * Holds the database adapter singleton instance
     *
     * @var    DatabaseAdapterInterface
     * @access public
     */
    public $_databaseAdapter;
    /**
     * Holds the database table being processed
     *
     * @var    string
     * @access protected
     */
    protected $_databaseTable;





    /**
     * Constructor
     *
     * @param  void
     * @return void
     */
    public function __construct() {

        // Get database adapter and error logger from the base class
        $this->_databaseAdapter = parent::databaseAdapter();
        parent::parseLanguageErrorLogFile();
    }

    /**
     * Inserts ball by ball info
     *
     * @param  string $bowlType
     * @param  string $batShotType
     * @param  int $runs
     * @param  string $comment
     * @param  int $batPlayerID
     * @param  int $bowlPlayerID
     * @param  int $gameID
     * @param  bool $isFour default FALSE
     * @param  bool $isSix default FALSE
     * @param  bool $isDismiss default FALSE
     * @param  string $disType default NULL
     * @param  bool $isExtra default FALSE
     *
     * @return bool
     */

    public function insertBallByBall($commentatorID, $bowlType, $batShotType, $runs, $comment, $batPlayerID, $bowlPlayerID, $gameID, $isDismiss=FALSE, $disType='', $isExtra=FALSE, $extraType='') {


        if (!is_bool($isDismiss)) {
            throw new Exception($this->lang_ini_array['ERRORS']['BooleanError']);
        }

        //Get current time
        $query = "SELECT CURTIME() AS time";
        $this->_databaseAdapter->query($query);
        $row = $this->_databaseAdapter->fetch();
        extract($row);
        $time = $row['time'];

        //Get id's relating to the batsman
        $this->_databaseTable = 'BATSMAN';
        $this->_databaseAdapter->select($this->_databaseTable, "PLAYER_PLAYER_ID='$batPlayerID'");
        $row = $this->_databaseAdapter->fetch();
        $batID = $row['BATSMAN_ID'];
        $batTeamID = $row['PLAYER_TEAM_TEAM_ID'];
        $gameID = $row['PLAYER_TEAM_GAME_GAME_ID'];

        //Determine if run is six or four
        if($runs == 4)
        {
            $isFour = TRUE;
        }
        else{
            $isFour = FALSE;
        }

        if($runs == 6)
        {
            $isSix = TRUE;
        }
        else{
            $isSix = FALSE;
        }

        //Get id's relating to the bowler
        $this->_databaseTable = 'BOWLER';
        $this->_databaseAdapter->select($this->_databaseTable, "PLAYER_PLAYER_ID='$bowlPlayerID'");
        $row = $this->_databaseAdapter->fetch();
        if(empty($row))
        {
            throw new Exception($this->lang_ini_array['ERRORS']['PlayerNotBowlerError']);
        };
        $bowlID = $row['BOWLER_ID'];
        $bowlTeamID = $row['PLAYER_TEAM_TEAM_ID'];
        $gameID2 = $row['PLAYER_TEAM_GAME_GAME_ID'];

        if ($gameID != $gameID2) {
            throw new Exception($this->lang_ini_array['ERRORS']['DifferentGamesError']);
        }

        $ballbyballData = array(
            'BALLBYBALL_ID' => '',
            'BALLBYBALL_BOW_BALLTYP' => $bowlType,
            'BALLBYBALL_BAT_SHOTTYP' => $batShotType,
            'BALLBYBALL_FOUR' => $isFour,
            'BALLBYBALL_SIX' => $isSix,
            'BALLBYBALL_RUNS' => $runs,
            'BALLBYBALL_COMNT' => $comment,
            'BALLBYBALL_DIS' => $isDismiss,
            'BALLBYBALL_DIS_TYP' => $disType,
            'BALLBYBALL_TIME' => $time,
            'BALLBYBALL_EXTR' => $isExtra,
            'BATSMAN_BATSMAN_ID' => $batID,
            'BATSMAN_PLAYER_PLAYER_ID' => $batPlayerID,
            'BATSMAN_PLAYER_TEAM_TEAM_ID' => $batTeamID,
            'BATSMAN_PLAYER_TEAM_GAME_GAME_ID' => $gameID,
            'BOWLER_BOWLER_ID' => $bowlID,
            'BOWLER_PLAYER_PLAYER_ID' => $bowlPlayerID,
            'BOWLER_PLAYER_TEAM_TEAM_ID' => $bowlTeamID,
            'COMMENTATOR_COMMENTATOR_ID' => $commentatorID,
            'BALLBYBALL_EXTRATYPE' => $extraType);

        $this->_databaseTable = 'BALLBYBALL';
        $id = $this->_databaseAdapter->insert($this->_databaseTable, $ballbyballData);
        $reponseArray = array();
        $reponseArray['success']=TRUE;
        $reponseArray['ballID']=$id;
        return $reponseArray;
    }

    /**
     * Inserts ball by ball info
     *
     * @param  string $bowlType
     * @param  string $batShotType
     * @param  int $runs
     * @param  string $comment
     * @param  int $batPlayerID
     * @param  int $bowlPlayerID
     * @param  int $gameID
     * @param  bool $isFour default FALSE
     * @param  bool $isSix default FALSE
     * @param  bool $isDismiss default FALSE
     * @param  string $disType default NULL
     * @param  bool $isExtra default FALSE
     *
     * @return bool
     */

    public function updateBallByBall($ballByBallId, $commentatorID, $bowlType, $batShotType, $runs, $comment, $batPlayerID, $bowlPlayerID, $gameID, $isDismiss=FALSE, $disType='', $isExtra=FALSE, $extraType='') {

        if (!is_bool($isDismiss)) {
            throw new Exception($this->lang_ini_array['ERRORS']['BooleanError']);
        }

        //Get current time
        $query = "SELECT CURTIME() AS time";
        $this->_databaseAdapter->query($query);
        $row = $this->_databaseAdapter->fetch();
        extract($row);
        $time = $row['time'];

        //Get id's relating to the batsman
        $this->_databaseTable = 'BATSMAN';
        $this->_databaseAdapter->select($this->_databaseTable, "PLAYER_PLAYER_ID='$batPlayerID'");
        $row = $this->_databaseAdapter->fetch();
        $batID = $row['BATSMAN_ID'];
        $batTeamID = $row['PLAYER_TEAM_TEAM_ID'];
        $gameID = $row['PLAYER_TEAM_GAME_GAME_ID'];

        //Determine if run is six or four
        if($runs == 4)
        {
            $isFour = TRUE;
        }
        else{
            $isFour = FALSE;
        }

        if($runs == 6)
        {
            $isSix = TRUE;
        }
        else{
            $isSix = FALSE;
        }

        //Get id's relating to the bowler
        $this->_databaseTable = 'BOWLER';
        $this->_databaseAdapter->select($this->_databaseTable, "PLAYER_PLAYER_ID='$bowlPlayerID'");
        $row = $this->_databaseAdapter->fetch();
        extract($row);
        $bowlID = $row['BOWLER_ID'];
        $bowlTeamID = $row['PLAYER_TEAM_TEAM_ID'];
        $gameID2 = $row['PLAYER_TEAM_GAME_GAME_ID'];

        if ($gameID != $gameID2) {
            throw new Exception($this->lang_ini_array['ERRORS']['DifferentGamesError']);
        }

        $ballbyballData = array(
            'BALLBYBALL_BOW_BALLTYP' => $bowlType,
            'BALLBYBALL_BAT_SHOTTYP' => $batShotType,
            'BALLBYBALL_FOUR' => $isFour,
            'BALLBYBALL_SIX' => $isSix,
            'BALLBYBALL_RUNS' => $runs,
            'BALLBYBALL_COMNT' => $comment,
            'BALLBYBALL_DIS' => $isDismiss,
            'BALLBYBALL_DIS_TYP' => $disType,
            'BALLBYBALL_TIME' => $time,
            'BALLBYBALL_EXTR' => $isExtra,
            'BATSMAN_BATSMAN_ID' => $batID,
            'BATSMAN_PLAYER_PLAYER_ID' => $batPlayerID,
            'BATSMAN_PLAYER_TEAM_TEAM_ID' => $batTeamID,
            'BATSMAN_PLAYER_TEAM_GAME_GAME_ID' => $gameID,
            'BOWLER_BOWLER_ID' => $bowlID,
            'BOWLER_PLAYER_PLAYER_ID' => $bowlPlayerID,
            'BOWLER_PLAYER_TEAM_TEAM_ID' => $bowlTeamID,
            'COMMENTATOR_COMMENTATOR_ID' => $commentatorID,
            'BALLBYBALL_EXTRATYPE' => $extraType);

        $this->_databaseTable = 'BALLBYBALL';
        $result = $this->_databaseAdapter->update($this->_databaseTable, $ballbyballData, "BALLBYBALL_ID=$ballByBallId");
        if(empty($result))
        {
            return false;
        }
        else
        return true;



    }

    /**
     * Returns the TEAM_ID (from the TEAM table) of the batting team
     *
     * @param  int $gameId
     * @param  int $innings
     *
     * @return int
     */

    public function getTeamIdOfBattingTeam($gameId, $innings)
    {

         $teamId = '';
         if($innings == '1'){
                            $query = "SELECT TEAM_ID FROM TEAM WHERE TEAM_BAT_FIRST IS TRUE AND GAME_GAME_ID = '$gameId'";
                            $this->_databaseAdapter->query($query);
                            $row = $this->_databaseAdapter->fetch();
                            $teamId = $row['TEAM_ID'];

                            if($teamId == NULL)
                            {
                                //throw new Exception($this->lang_ini_array['ERRORS']['WrongGameIdError']);
                            }
                            return $teamId;

                       }
                    else   if($innings == '2'){
                           $query = "SELECT TEAM_ID FROM TEAM WHERE TEAM_BAT_FIRST IS FALSE AND GAME_GAME_ID = '$gameId'";
                            $this->_databaseAdapter->query($query);
                            $row = $this->_databaseAdapter->fetch();
                            $teamId = $row['TEAM_ID'];
                            if(empty($teamId))
                            {
                                //throw new Exception($this->lang_ini_array['ERRORS']['WrongGameIdError']);
                            }
                            return $teamId;
                       }

                       else {
                          // throw new Exception($this->lang_ini_array['ERRORS']['InvalidInningsError']);

                       }
    }

    /**
     * Returns the TEAM_ID (from the TEAM table) of the bowling team
     *
     * @param  int $gameId
     * @param  int $innings
     *
     * @return int
     */

        public function getTeamIdOfBowlingTeam($gameId, $innings)
    {

         $teamId = '';
         if($innings == '1'){
                            $query = "SELECT TEAM_ID FROM TEAM WHERE TEAM_BAT_FIRST IS FALSE AND GAME_GAME_ID = '$gameId'";
                            $this->_databaseAdapter->query($query);
                            $row = $this->_databaseAdapter->fetch();
                            $teamId = $row['TEAM_ID'];
                            if(empty($teamId))
                            {
                                //throw new Exception($this->lang_ini_array['ERRORS']['WrongGameIdError']);
                            }
                            return $teamId;


                       }
                       if($innings == '2'){
                           $query = "SELECT TEAM_ID FROM TEAM WHERE TEAM_BAT_FIRST IS TRUE AND GAME_GAME_ID = '$gameId'";
                            $this->_databaseAdapter->query($query);
                            $row = $this->_databaseAdapter->fetch();
                            $teamId = $row['TEAM_ID'];
                            if(empty($teamId))
                            {
                                //throw new Exception($this->lang_ini_array['ERRORS']['WrongGameIdError']);
                            }
                            return $teamId;
                       }

                       else {
                           throw new Exception($this->lang_ini_array['ERRORS']['InvalidInningsError']);

                       }


    }

     /**
     * Returns total number of balls including extras
     *
     * @param  int $gameId
     * @param  int $teamId
     *
     * @return int
     */

    public function getTotalNumberOfBalls($gameId, $teamId)
    {
        $query = "SELECT COUNT(*) AS count FROM $this->_databaseTable WHERE BATSMAN_PLAYER_TEAM_GAME_GAME_ID = '$gameId' AND BATSMAN_PLAYER_TEAM_TEAM_ID = '$teamId'";
        $this->_databaseAdapter->query($query);
        $result = $this->_databaseAdapter->fetch();
        $numberOfTotalBalls = $result['count'];
        return $numberOfTotalBalls;
    }

    /**
     * Returns number of balls excluding extras
     *
     * @param  int $gameId
     * @param  int $innings
     *
     * @return int
     */


    public function getNumberOfBalls($gameId,$innings) {

        $teamId = $this->getTeamIdOfBattingTeam($gameId, $innings);
        //Count number of extras
        $numberOfExtras = $this->getNumberOfExtras($gameId, $innings);

        $numberOfTotalBalls = $this->getTotalNumberOfBalls($gameId, $teamId);

        $numberOfBalls = $numberOfTotalBalls - $numberOfExtras;
        return $numberOfBalls;

    }

     public function getNumberOfExtras($gameId, $innings) {

$teamId = $this->getTeamIdOfBattingTeam($gameId, $innings);

//Count number of extras
        $this->_databaseTable = 'BALLBYBALL';
        $query = "SELECT COUNT(*) AS count FROM $this->_databaseTable WHERE BALLBYBALL_EXTR IS TRUE AND BATSMAN_PLAYER_TEAM_GAME_GAME_ID = '$gameId' AND BATSMAN_PLAYER_TEAM_TEAM_ID = '$teamId'";
        $this->_databaseAdapter->query($query);
        $result = $this->_databaseAdapter->fetch();
        $numberOfExtras = $result['count'];

        return $numberOfExtras;

    }

               public function getNumberOfDismissals($gameId) {

        //Count number of extras
        $this->_databaseTable = 'BALLBYBALL';
        $query = "SELECT COUNT(*) AS count FROM $this->_databaseTable WHERE BALLBYBALL_DIS IS TRUE AND BATSMAN_PLAYER_TEAM_GAME_GAME_ID = '$gameId'";
        $this->_databaseAdapter->query($query);
        $result = $this->_databaseAdapter->fetch();
        $numberOfDismissals = $result['count'];
        return $numberOfDismissals;
    }

    /**
     * Returns current over
     *
     * @param  int $gameId
     * @param  int $innings
     *
     * @return float
     */

                 public function getCurrentOver($gameId,$innings) {

        $numberOfBalls = $this->getNumberOfBalls($gameId,$innings);
        $over = $this->calculateOver($numberOfBalls);
        return $over;
    }

    public function calculateOver($numberOfBalls)
    {
         $wholeOver = $numberOfBalls/6;
        $wholeOverDecimal = floor($wholeOver);
        //$ballsElapsedInOver = $this->getNumberOfBalls($gameId) % 6;
        $ballsElapsedInOver = $wholeOver - $wholeOverDecimal;
        if($ballsElapsedInOver > 0 AND $ballsElapsedInOver < 0.168)
        {
           $ballsElapsedInOver = 1;
        }
        if($ballsElapsedInOver > 0.167 AND $ballsElapsedInOver < 0.334)
        {
           $ballsElapsedInOver = 2;
        }

        if($ballsElapsedInOver == 0.5)
        {
           $ballsElapsedInOver = 3;
        }

        if($ballsElapsedInOver > 0.5 AND $ballsElapsedInOver < 0.68)
        {
           $ballsElapsedInOver = 4;
        }

        if($ballsElapsedInOver > 0.68 AND $ballsElapsedInOver < 1)
        {
           $ballsElapsedInOver = 5;
        }

        return $wholeOverDecimal.'.'.$ballsElapsedInOver;
    }

                     public function getInnings($gameId) {


                     //Count number of extras
        $this->_databaseTable = 'BALLBYBALL';
        $query = "SELECT COUNT(*) AS count FROM $this->_databaseTable WHERE BALLBYBALL_EXTR IS TRUE AND BATSMAN_PLAYER_TEAM_GAME_GAME_ID = '$gameId'";
        $this->_databaseAdapter->query($query);
        $result = $this->_databaseAdapter->fetch();
        $numberOfExtras = $result['count'];

        $query = "SELECT COUNT(*) AS count FROM $this->_databaseTable WHERE BATSMAN_PLAYER_TEAM_GAME_GAME_ID = '$gameId'";
        $this->_databaseAdapter->query($query);
        $result = $this->_databaseAdapter->fetch();
        $numberOfTotalBalls = $result['count'];
        $numberOfBalls = $numberOfTotalBalls - $numberOfExtras;

        if($numberOfBalls  >= 300 OR $this->getNumberOfDismissals($gameId) >= 10)
        //if($numberOfBalls  >= 60 OR $this->getNumberOfDismissals($gameId) >= 10)
        {
            return '2';
        }
        else{
            return '1';
        }
    }

    /**
     * Returns information pertaining to the current last ball of the innings
     *
     * @param  int $gameId
     *
     * @return mixed
     */

                         public function getLastBallInfo($gameId) {
                         $this->_databaseTable = 'BALLBYBALL';
                         $lastBallId = $this->getLastBallId($gameId);
                         $query = "SELECT * FROM $this->_databaseTable WHERE BATSMAN_PLAYER_TEAM_GAME_GAME_ID = '$gameId'AND BALLBYBALL_ID = '$lastBallId'";
                         $this->_databaseAdapter->query($query);
                         $row = $this->_databaseAdapter->fetch();

                         //Gets bowler player id
                         $bowlerPlayerId = $row['BOWLER_PLAYER_PLAYER_ID'];
                         $query = "SELECT * FROM PLAYER WHERE PLAYER_ID = '$bowlerPlayerId'";
                         $this->_databaseAdapter->query($query);
                         $bowlerRow = $this->_databaseAdapter->fetch();

                         //Get bowler name
                         $bowlerPlayerPoolId = $bowlerRow['PLAYER_POOL_PLAYER_POOL_ID'];
                         $query = "SELECT PLAYER_POOL_FNAME, PLAYER_POOL_LNAME FROM PLAYER_POOL WHERE PLAYER_POOL_ID = '$bowlerPlayerPoolId'";
                         $this->_databaseAdapter->query($query);
                         $bowlerRow = $this->_databaseAdapter->fetch();

                         $row['BOWLER_FIRST_NAME'] = $bowlerRow['PLAYER_POOL_FNAME'];
                         $row['BOWLER_LAST_NAME'] = $bowlerRow['PLAYER_POOL_LNAME'];

                         //Get bowler stats
                         $bowlerStats = $this->getBowlerScoreCard($gameId, $bowlerPlayerId);
                         $row['BOWLER_BALLS'] = $bowlerStats['balls'];
                         $row['BOWLER_WICKETS'] = $bowlerStats['wickets'];
                         $row['BOWLER_RUNS'] = $bowlerStats['runs'];
                         $row['BOWLER_OVER'] = $bowlerStats['over'];
                         $row['BOWLER_ECONOMY'] = $bowlerStats['economy'];
                         $row['BOWLER_EXTRATYPES'] = $bowlerStats['extra type'];

                         //Get facing batsman player pool id
                         $facingBatsmanPlayerId = $row['BATSMAN_PLAYER_PLAYER_ID'];
                         $query = "SELECT * FROM PLAYER WHERE PLAYER_ID = '$facingBatsmanPlayerId'";
                         $this->_databaseAdapter->query($query);
                         $batsmanRow1 = $this->_databaseAdapter->fetch();

                         //Get facing batsman name
                         $batsmanPlayerPoolId = $batsmanRow1['PLAYER_POOL_PLAYER_POOL_ID'];
                         $query = "SELECT PLAYER_POOL_FNAME, PLAYER_POOL_LNAME FROM PLAYER_POOL WHERE PLAYER_POOL_ID = '$batsmanPlayerPoolId'";
                         $this->_databaseAdapter->query($query);
                         $batsmanRow2 = $this->_databaseAdapter->fetch();

                         //Get facing batsman stats
                         $batsmanStats = $this->getBatsmanScoreCard($gameId, $facingBatsmanPlayerId);

                         $row['FACING_BATSMAN_FIRST_NAME'] = $batsmanRow2['PLAYER_POOL_FNAME'];
                         $row['FACING_BATSMAN_LAST_NAME'] = $batsmanRow2['PLAYER_POOL_LNAME'];
                         $row['FACING_BATSMAN_BALLS'] = $batsmanStats['balls'];
                         $row['FACING_BATSMAN_RUNS'] = $batsmanStats['runs'];
                         $row['FACING_BATSMAN_FOURS'] = $batsmanStats['Fours'];
                         $row['FACING_BATSMAN_SIXES'] = $batsmanStats['Sixes'];
                         $row['FACING_BATSMAN_SR'] = $batsmanStats['SR'];

                         //Get batsman player team
                         $batsmanTeamId = $row['BATSMAN_PLAYER_TEAM_TEAM_ID'];

                         //Get partner batsman player id
                         $battingPair = $this->getBattingPair($gameId);
                         if($battingPair[0]['PLAYER_ID'] == $facingBatsmanPlayerId)
                         {
                             $partnerBatsmanPlayerId = $battingPair[1]['PLAYER_ID'];
                         }
                         else{
                             $partnerBatsmanPlayerId = $battingPair[0]['PLAYER_ID'];
                         }

                         //Get partner batsman player pool id
                         $query = "SELECT * FROM PLAYER WHERE PLAYER_ID = '$partnerBatsmanPlayerId'";
                         $this->_databaseAdapter->query($query);
                         $batsmanRow4 = $this->_databaseAdapter->fetch();

                         //Get partner batsman name
                         $unfacingBatsmanPlayerPoolId = $batsmanRow4['PLAYER_POOL_PLAYER_POOL_ID'];
                         $query = "SELECT PLAYER_POOL_FNAME, PLAYER_POOL_LNAME FROM PLAYER_POOL WHERE PLAYER_POOL_ID = '$unfacingBatsmanPlayerPoolId'";
                         $this->_databaseAdapter->query($query);
                         $batsmanRow5 = $this->_databaseAdapter->fetch();

                         //Get partner batsman stats
                         $partnerBatsmanStats = $this->getBatsmanScoreCard($gameId, $partnerBatsmanPlayerId);

                         $row['UNFACING_BATSMAN_FIRST_NAME'] = $batsmanRow5['PLAYER_POOL_FNAME'];
                         $row['UNFACING_BATSMAN_LAST_NAME'] = $batsmanRow5['PLAYER_POOL_LNAME'];
                         $row['UNFACING_BATSMAN_PLAYER_ID'] = $partnerBatsmanPlayerId;
                         $row['UNFACING_BATSMAN_BALLS'] = $partnerBatsmanStats['balls'];
                         $row['UNFACING_BATSMAN_RUNS'] = $partnerBatsmanStats['runs'];
                         $row['UNFACING_BATSMAN_FOURS'] = $partnerBatsmanStats['Fours'];
                         $row['UNFACING_BATSMAN_SIXES'] = $partnerBatsmanStats['Sixes'];
                         $row['UNFACING_BATSMAN_SR'] = $partnerBatsmanStats['SR'];


                         return $row;
    }

    /**
     * Returns number of runs
     *
     * @param  int $gameId
     * @param  int $teamId
     *
     * @return int
     */

    public function getRuns($gameId, $teamId)
    {
        $this->_databaseTable = 'BALLBYBALL';
                           $query = "SELECT SUM(BALLBYBALL_RUNS) AS runs FROM $this->_databaseTable WHERE BATSMAN_PLAYER_TEAM_GAME_GAME_ID = '$gameId' AND BATSMAN_PLAYER_TEAM_TEAM_ID = '$teamId'";
                           $this->_databaseAdapter->query($query);
                           $result = $this->_databaseAdapter->fetch();
                           $numberOfRuns = $result['runs'];
                           return $numberOfRuns;
    }

    /**
     * Returns number of fallen wickets
     *
     * @param  int $gameId
     * @param  int $teamId
     *
     * @return int
     */

    public function getNumberOfFallenWickets($gameId, $teamId)
    {
        $query = "SELECT COUNT(*) AS count FROM $this->_databaseTable WHERE BATSMAN_PLAYER_TEAM_GAME_GAME_ID = '$gameId' AND BALLBYBALL_DIS IS TRUE AND BATSMAN_PLAYER_TEAM_TEAM_ID = '$teamId'";
        $this->_databaseAdapter->query($query);
        $resultWickets = $this->_databaseAdapter->fetch();
        $numberOfWicketsFallen = $resultWickets['count'];
        return $numberOfWicketsFallen;
    }

    /**
     * Returns current score comprising overs, runs, and wickets. For each innings
     *
     * @param  int $gameId
     *
     * @return mixed
     */

                       public function getCurrentScore($gameId) {

                           $currentScore = array();

                           $currentScore['Innings'] = $this->getInnings($gameId);

                       //For first innings
                       $teamId = $this->getTeamIdOfBattingTeam($gameId, '1');

                       //Get number of runs
                           $numberOfRuns = $this->getRuns($gameId, $teamId);

                           $overs = $this->getCurrentOver($gameId,'1');

                           //Get number of fallen wickets
                           $numberOfWicketsFallen = $this->getNumberOfFallenWickets($gameId, $teamId);

                           $currentScore['firstInnings'] = array('runs'=>$numberOfRuns,'overs'=>$overs, 'wickets'=>$numberOfWicketsFallen);

                           //For second innings
                       $teamId2 = $this->getTeamIdOfBattingTeam($gameId, '2');

                       //Get number of runs
                            $numberOfRuns2 = $this->getRuns($gameId, $teamId2);

                            //If number of runs is null, return 0
                            if($numberOfRuns2 == ''){
                                $numberOfRuns2 = '0';
                            }

                           $secondInningsOvers = $this->getCurrentOver($gameId,'2');

                           //Get number of fallen wickets
                           $numberOfWicketsFallen2 = $this->getNumberOfFallenWickets($gameId, $teamId2);

                           $currentScore['secondInnings'] = array('runs'=>$numberOfRuns2,'overs'=>$secondInningsOvers, 'wickets'=>$numberOfWicketsFallen2);
                           return $currentScore;




    }

    /**
     * Returns information pertaining to the wicket keeper of the current innings
     *
     * @param  int $gameId
     *
     * @return mixed
     */

                              public function getWicketKeeper($gameId) {


                       $innings = $this->getInnings($gameId);
                       $teamId = $this->getTeamIdOfBowlingTeam($gameId, $innings);

                       $query = "SELECT p.PLAYER_ID,
                                 pp.PLAYER_POOL_FNAME, pp.PLAYER_POOL_LNAME, pp.PLAYER_POOL_FLDNG
                                 FROM PLAYER AS p
                                 LEFT JOIN PLAYER_POOL AS pp ON p.PLAYER_POOL_PLAYER_POOL_ID = pp.PLAYER_POOL_ID
                                 WHERE p.TEAM_TEAM_ID = '$teamId'";

                       $resultsArray = array();
                       $this->_databaseAdapter->query($query);
                       $counter = 0;

                       while ($row = $this->_databaseAdapter->fetch()) {
                                extract($row);
                               $resultsArray[]= $row;
                               $fieldingPosition = $resultsArray[$counter]['PLAYER_POOL_FLDNG'];
                               if (preg_match("/^(wicket)[\- ]?(keeper)$/i", $fieldingPosition)>0)
                               {
                                   return $resultsArray[$counter];
                               }
                               $counter++;
                            }

    }

    /**
     * Returns information pertaining to the bowlers of the current innings
     *
     * @param  int $gameId
     *
     * @return mixed
     */

                          public function getBowlers($gameId) {


                       $innings = $this->getInnings($gameId);
                       $teamId = $this->getTeamIdOfBowlingTeam($gameId, $innings);

                       $query = "SELECT p.PLAYER_ID, pp.PLAYER_POOL_FNAME, pp.PLAYER_POOL_LNAME, pp.PLAYER_POOL_BOWLSTYL
                                 FROM BOWLER AS b
                                 LEFT JOIN PLAYER AS p ON b.PLAYER_PLAYER_ID = p.PLAYER_ID
                                 LEFT JOIN PLAYER_POOL AS pp ON p.PLAYER_POOL_PLAYER_POOL_ID = pp.PLAYER_POOL_ID
                                 WHERE PLAYER_TEAM_TEAM_ID = '$teamId'";

                       $bowlersArray = array();
                       $this->_databaseAdapter->query($query);
                        while ($row = $this->_databaseAdapter->fetch()) {
                                extract($row);
                               $bowlersArray[]= $row;
                            }


        return $bowlersArray;



    }

    /**
     * Returns information of current batting pair
     *
     * @param  int $gameId
     *
     * @return mixed
     */

                       public function getBattingPair($gameId) {


                       $innings = $this->getInnings($gameId);
                       $teamId = $this->getTeamIdOfBattingTeam($gameId, $innings);


                       $query = "SELECT p.PLAYER_ID
                                 FROM PLAYER AS p
                                 LEFT JOIN PLAYER_POOL AS pp ON p.PLAYER_POOL_PLAYER_POOL_ID = pp.PLAYER_POOL_ID
                                 WHERE p.TEAM_GAME_GAME_ID='$gameId' AND p.TEAM_TEAM_ID = '$teamId'
                                 ORDER BY p.PLAYER_BAT_ORDR ASC";

                       $actualBatsmanOrderArray = array();
                       $this->_databaseAdapter->query($query);
                        while ($row = $this->_databaseAdapter->fetch()) {
         extract($row);
         $actualBatsmanOrderArray[]= $row['PLAYER_ID'];
        }



                               $query = "SELECT BATSMAN_PLAYER_PLAYER_ID FROM BALLBYBALL WHERE BALLBYBALL_DIS IS TRUE AND BATSMAN_PLAYER_TEAM_GAME_GAME_ID = '$gameId' AND BATSMAN_PLAYER_TEAM_TEAM_ID = '$teamId'
                                   ORDER BY BALLBYBALL_ID ASC";

                       $dimissedBatsmanOrderArray = array();
                       $this->_databaseAdapter->query($query);
                        while ($row = $this->_databaseAdapter->fetch()) {
         extract($row);
         $dimissedBatsmanOrderArray[]= $row['BATSMAN_PLAYER_PLAYER_ID'];
        }

        $undismissedBatsmanArray = array_diff($actualBatsmanOrderArray, $dimissedBatsmanOrderArray);

        reset($undismissedBatsmanArray);
        $firstBatsmanID = current($undismissedBatsmanArray);
        $secondBatsmanID = next($undismissedBatsmanArray);

        $query = "SELECT p.PLAYER_ID, p.PLAYER_BAT_ORDR,
                  pp.PLAYER_POOL_FNAME, pp.PLAYER_POOL_LNAME
                  FROM PLAYER AS p
                  LEFT JOIN PLAYER_POOL AS pp ON p.PLAYER_POOL_PLAYER_POOL_ID = pp.PLAYER_POOL_ID
                  WHERE p.TEAM_GAME_GAME_ID='$gameId' AND p.PLAYER_ID = '$firstBatsmanID' OR p.PLAYER_ID = '$secondBatsmanID'";

                  $results = array();
                  $this->_databaseAdapter->query($query);
                  while ($row = $this->_databaseAdapter->fetch()) {
                   extract($row);
                   $results[] = $row;
                  }

        return $results;



    }

                       public function getBattingAndBowlingTeamsForInnings($gameId, $innings) {
                       $teams = array();
                       $query = "SELECT t.TEAM_ID,
                  tp.TEAM_POOL_NAME, tp.TEAM_POOL_SNAME
                  FROM GAME AS g
                  LEFT JOIN TEAM AS t ON g.GAME_ID = t.GAME_GAME_ID
                  LEFT JOIN TEAM_POOL AS tp ON tp.TEAM_POOL_ID = t.TEAM_POOL_TEAM_POOL_ID
                  WHERE g.GAME_ID='$gameId'
                  ORDER BY t.TEAM_BAT_FIRST DESC";

                    $resultArray = array();
                    $this->_databaseAdapter->query($query);
        while ($row = $this->_databaseAdapter->fetch()) {
         extract($row);
         $resultArray[]= $row;
        }
        $i=0;
        $j=1;

        if($innings == '1')
        {

                       $teams['batting'] = $resultArray[$i];
                       $teams['bowling'] = $resultArray[$j];
                       return $teams;
        }
        if($innings == '2')
        {
            $teams['batting'] = $resultArray[$j];
            $teams['bowling'] = $resultArray[$i];
            return $teams;
        }


    }

    /**
     * Returns information of batting and bowling teams of a particular game
     *
     * @param  int $gameId
     *
     * @return mixed
     */


                   public function getBattingAndBowlingTeams($gameId) {

                   //Get innings
                   $innings = $this->getInnings($gameId);
                       $teams = array();
                       $query = "SELECT t.TEAM_ID,
                  tp.TEAM_POOL_NAME, tp.TEAM_POOL_SNAME
                  FROM GAME AS g
                  LEFT JOIN TEAM AS t ON g.GAME_ID = t.GAME_GAME_ID
                  LEFT JOIN TEAM_POOL AS tp ON tp.TEAM_POOL_ID = t.TEAM_POOL_TEAM_POOL_ID
                  WHERE g.GAME_ID='$gameId'
                  ORDER BY t.TEAM_BAT_FIRST DESC";

                    $resultArray = array();
                    $this->_databaseAdapter->query($query);
        while ($row = $this->_databaseAdapter->fetch()) {
         extract($row);
         $resultArray[]= $row;
        }

        if($innings == '1')
        {
                       $teams['batting'] = $resultArray[0];
                       $teams['bowling'] = $resultArray[1];
                       return $teams;
        }

        if($innings == '2')
        {
                       $teams['batting'] = $resultArray[1];
                       $teams['bowling'] = $resultArray[0];
                       return $teams;
        }

    }

                      public function getPlayersOfBowlingTeam($gameId) {
                       
                       $innings = $this->getInnings($gameId);
                       $teams = $this->getBattingAndBowlingTeamsForInnings($gameId, $innings);
                       //$teams = $this->getBattingAndBowlingTeams($gameId);
                       $bowlingTeam = $teams['bowling'];
                       $teamId = $bowlingTeam['TEAM_ID'];

                       $query = "SELECT pp.PLAYER_POOL_ID, pp.PLAYER_POOL_FNAME, pp.PLAYER_POOL_LNAME,
                                 p.PLAYER_ID
                                 FROM PLAYER_POOL AS pp
                                 LEFT JOIN PLAYER AS p ON pp.PLAYER_POOL_ID = p.PLAYER_POOL_PLAYER_POOL_ID
                                 WHERE p.TEAM_TEAM_ID='$teamId'";

                      $resultArray = array();
                      $this->_databaseAdapter->query($query);
                      while ($row = $this->_databaseAdapter->fetch()) {
                      extract($row);
                      $resultArray[]= $row;
                      }
                      return $resultArray;



    }

                             public function getSummaryBattingScoreCard($gameId, $innings) {




                          $teamId = $this->getTeamIdOfBattingTeam($gameId, $innings);

                       if(empty($teamId)){
                           //throw new Exception($this->lang_ini_array['ERRORS']['NonExistentGameError']);
                       }

                       $currentBattingPair = $this->getBattingPair($gameId);

                       $final = array();

                      foreach ($currentBattingPair as $key => $value) {
                          $playerId = $value['PLAYER_ID'];
                           $query = "select pp.PLAYER_POOL_ID, pp.PLAYER_POOL_FNAME, pp.PLAYER_POOL_LNAME, bb.BALLBYBALL_DIS_TYP,
                               COUNT(bb.BALLBYBALL_ID) AS balls, bb.BALLBYBALL_DIS, SUM(bb.BALLBYBALL_RUNS) AS runs,
                               SUM(bb.BALLBYBALL_FOUR) AS Fours,SUM(bb.BALLBYBALL_SIX) AS Sixes
                               FROM BALLBYBALL AS bb
                               LEFT JOIN BATSMAN AS b ON bb.BATSMAN_BATSMAN_ID = b.BATSMAN_ID
                               LEFT JOIN PLAYER AS p ON b.PLAYER_PLAYER_ID = p.PLAYER_ID
                               LEFT JOIN PLAYER_POOL AS pp ON p.PLAYER_POOL_PLAYER_POOL_ID = pp.PLAYER_POOL_ID
                               WHERE bb.BALLBYBALL_EXTR IS FALSE AND bb.BATSMAN_PLAYER_TEAM_GAME_GAME_ID = '$gameId' AND bb.BATSMAN_PLAYER_TEAM_TEAM_ID = '$teamId' AND bb.BATSMAN_PLAYER_PLAYER_ID = '$playerId'
                               ";
                          $this->_databaseAdapter->query($query);
                          $row = $this->_databaseAdapter->fetch();
                          $resultArray2 = array();
                          extract($row);
                          $resultArray2[]= $row;
                          $final[$key]['player pool id'] = $resultArray2[0]['PLAYER_POOL_ID'];
                          $final[$key]['player first name'] = $resultArray2[0]['PLAYER_POOL_FNAME'];
                          $final[$key]['player last name'] = $resultArray2[0]['PLAYER_POOL_LNAME'];
                          $final[$key]['balls'] = $resultArray2[0]['balls'];
                          $final[$key]['runs'] = $resultArray2[0]['runs'];
                          $final[$key]['fours'] = $resultArray2[0]['Fours'];
                          $final[$key]['sixes'] = $resultArray2[0]['Sixes'];

                          if($resultArray2[0]['balls'] == 0)
                          {


                          $final[$key]['strike rate'] = 0;
                          }
                          else{
                              $final[$key]['strike rate'] = ($resultArray2[0]['runs']/$resultArray2[0]['balls'])*100;
                          }

                      }

                      return $final;


    }


    /**
     * Returns full batting score card
     *
     * @param  int $gameId
     * @param  int $innings
     *
     * @return mixed
     */


                         public function getFullBattingScoreCard($gameId, $innings) {

                         $teamId = $this->getTeamIdOfBattingTeam($gameId, $innings);

                     $query = "select pp.PLAYER_POOL_ID, pp.PLAYER_POOL_FNAME, pp.PLAYER_POOL_LNAME, bb.BALLBYBALL_DIS_TYP, p.PLAYER_ID,
                               COUNT(bb.BALLBYBALL_ID) AS balls, SUM(bb.BALLBYBALL_DIS) AS dismissed, SUM(bb.BALLBYBALL_RUNS) AS runs,
                               SUM(bb.BALLBYBALL_FOUR) AS Fours,SUM(bb.BALLBYBALL_SIX) AS Sixes
                               FROM BALLBYBALL AS bb
                               LEFT JOIN BATSMAN AS b ON bb.BATSMAN_BATSMAN_ID = b.BATSMAN_ID
                               LEFT JOIN PLAYER AS p ON b.PLAYER_PLAYER_ID = p.PLAYER_ID
                               LEFT JOIN PLAYER_POOL AS pp ON p.PLAYER_POOL_PLAYER_POOL_ID = pp.PLAYER_POOL_ID
                               WHERE bb.BALLBYBALL_EXTR IS FALSE AND bb.BATSMAN_PLAYER_TEAM_GAME_GAME_ID = '$gameId' AND bb.BATSMAN_PLAYER_TEAM_TEAM_ID = '$teamId'
                               GROUP BY p.PLAYER_BAT_ORDR ASC";


                      $resultArray = array();
                      $this->_databaseAdapter->query($query);
                      while ($row = $this->_databaseAdapter->fetch()) {
                      extract($row);
                      $resultArray[]= $row;
                      }

                      //Calculate strike rate

                      foreach ($resultArray as $key => $value) {
                          $resultArray[$key]['SR'] = ($resultArray[$key]['runs']/$resultArray[$key]['balls'])*100;
                          // For unit testing
                          $resultArray[$key]['SR'] = round($resultArray[$key]['SR'], 1);
                      }

                      foreach ($resultArray as $key => $value) {
                          $batsPlayerId = $resultArray[$key]['PLAYER_ID'];
                          $query = "SELECT BALLBYBALL_DIS_TYP FROM BALLBYBALL WHERE BALLBYBALL_DIS_TYP != '' AND BATSMAN_PLAYER_PLAYER_ID = '$batsPlayerId'";
                          $row = array();
                          $this->_databaseAdapter->query($query);
                          $row = $this->_databaseAdapter->fetch();
                          $resultArray[$key]['BALLBYBALL_DIS_TYP'] = $row['BALLBYBALL_DIS_TYP'];

                      }

                      return $resultArray;


    }


    public function getBatsmanScoreCard($gameId, $batsmanPlayerId) {


                     $query = "select COUNT(bb.BALLBYBALL_ID) AS balls, SUM(bb.BALLBYBALL_DIS) AS dismissed, SUM(bb.BALLBYBALL_RUNS) AS runs,
                               SUM(bb.BALLBYBALL_FOUR) AS Fours,SUM(bb.BALLBYBALL_SIX) AS Sixes
                               FROM BALLBYBALL AS bb
                               WHERE bb.BALLBYBALL_EXTR IS FALSE AND bb.BATSMAN_PLAYER_TEAM_GAME_GAME_ID = '$gameId' AND bb.BATSMAN_PLAYER_PLAYER_ID = '$batsmanPlayerId'";

                      $this->_databaseAdapter->query($query);
                      $row = $this->_databaseAdapter->fetch();

                      //Calculate strike rate
                          $row['SR'] = ($row['runs']/$row['balls'])*100;
                          // For unit testing
                          $row['SR'] = round($row['SR'], 1);
                    
                          return $row;


    }


    /**
     * Returns full bowling score card
     *
     * @param  int $gameId
     * @param  int $innings
     *
     * @return mixed
     */

                         public function getFullBowlingScoreCard($gameId, $innings) {

                         $teamId = $this->getTeamIdOfBowlingTeam($gameId, $innings);

                     $query = "select pp.PLAYER_POOL_ID, pp.PLAYER_POOL_FNAME, pp.PLAYER_POOL_LNAME, p.PLAYER_ID,
                               COUNT(bb.BALLBYBALL_ID) AS balls, SUM(bb.BALLBYBALL_DIS) AS wickets, SUM(bb.BALLBYBALL_RUNS) AS runs, bb.BOWLER_BOWLER_ID, SUM(bb.BALLBYBALL_EXTR) AS extras
                               FROM BALLBYBALL AS bb
                               LEFT JOIN BOWLER AS b ON bb.BOWLER_BOWLER_ID = b.BOWLER_ID
                               LEFT JOIN PLAYER AS p ON b.PLAYER_PLAYER_ID = p.PLAYER_ID
                               LEFT JOIN PLAYER_POOL AS pp ON p.PLAYER_POOL_PLAYER_POOL_ID = pp.PLAYER_POOL_ID
                               WHERE bb.BATSMAN_PLAYER_TEAM_GAME_GAME_ID = '$gameId' AND bb.BOWLER_PLAYER_TEAM_TEAM_ID = '$teamId'
                               GROUP BY bb.BOWLER_BOWLER_ID ASC";


                      $resultArray = array();
                      $this->_databaseAdapter->query($query);
                      while ($row = $this->_databaseAdapter->fetch()) {
                      extract($row);
                      $resultArray[]= $row;
                      }


                      $final = array();

                      foreach ($resultArray as $key => $value) {

                          $final[$key]['player pool id'] = $value['PLAYER_POOL_ID'];
                          $final[$key]['player first name'] = $value['PLAYER_POOL_FNAME'];
                          $final[$key]['player last name'] = $value['PLAYER_POOL_LNAME'];
                          $final[$key]['balls'] = $value['balls'] - $value['extras'];
                          $final[$key]['wickets'] = $value['wickets'];
                          $final[$key]['runs'] = $value['runs']+ $value['extras'];
                          $final[$key]['player id'] = $value['PLAYER_ID'];
        $numberOfBalls = $final[$key]['balls'];
        $over = $this->calculateOver($numberOfBalls);
          $final[$key]['over'] = $over;

          //Calculate economy
          $runs = $final[$key]['runs'];
          $final[$key]['economy'] = $runs/$over;
          $final[$key]['economy'] = round($final[$key]['economy'], 1);
          //For unit testing


                           $bowlPlayerId = $value['PLAYER_ID'];

                           $query = "SELECT BALLBYBALL_EXTRATYPE FROM BALLBYBALL WHERE BOWLER_PLAYER_PLAYER_ID='$bowlPlayerId' AND BALLBYBALL_EXTRATYPE !='0'";
                          //Correct version
                          //$query = "SELECT BALLBYBALL_EXTRATYPE FROM BALLBYBALL WHERE BOWLER_PLAYER_PLAYER_ID='$bowlPlayerId' AND BALLBYBALL_EXTRATYPE !=''";

                         $row = array();
                      $this->_databaseAdapter->query($query);
                      $counter = 0;
                      while ($row = $this->_databaseAdapter->fetch()) {
                      extract($row);
                      $final[$key]['extra type'][$counter]= $row['BALLBYBALL_EXTRATYPE'];
                      $counter++;
                      }
//
//
                     }


//
                      return $final;


    }

    /**
     * Returns score card
     *
     * @param  int $gameId
     * @param  int $innings
     *
     * @return mixed
     */

                         public function getBowlerScoreCard($gameId, $bowlerPlayerId) {


                     $query = "select COUNT(bb.BALLBYBALL_ID) AS balls, SUM(bb.BALLBYBALL_DIS) AS wickets, SUM(bb.BALLBYBALL_RUNS) AS runs,SUM(bb.BALLBYBALL_EXTR) AS extras
                               FROM BALLBYBALL AS bb
                               WHERE bb.BATSMAN_PLAYER_TEAM_GAME_GAME_ID = '$gameId' AND bb.BOWLER_PLAYER_PLAYER_ID = '$bowlerPlayerId'";

                      $this->_databaseAdapter->query($query);
                      $row = $this->_databaseAdapter->fetch();


                          $row['balls'] = $row['balls'] - $row['extras'];
                          $row['runs'] = $row['runs']+ $row['extras'];
                          $numberOfBalls = $row['balls'];
                          $over = $this->calculateOver($numberOfBalls);
                          $row['over'] = $over;
          //Calculate economy
                          $runs = $row['runs'];
                          $row['economy'] = $runs/$over;
                          $row['economy'] = round($row['economy'], 1);
          //For unit testing

                           $query = "SELECT BALLBYBALL_EXTRATYPE FROM BALLBYBALL WHERE BOWLER_PLAYER_PLAYER_ID='$bowlerPlayerId' AND BALLBYBALL_EXTRATYPE !='0'";
                          //Correct version
                          //$query = "SELECT BALLBYBALL_EXTRATYPE FROM BALLBYBALL WHERE BOWLER_PLAYER_PLAYER_ID='$bowlPlayerId' AND BALLBYBALL_EXTRATYPE !=''";

                      $row2 = array();
                      $this->_databaseAdapter->query($query);
                      $counter = 0;
                      while ($row2 = $this->_databaseAdapter->fetch()) {
                      extract($row2);
                      $row['extra type'][$counter]= $row2['BALLBYBALL_EXTRATYPE'];
                      $counter++;
                      }
//
//



//
                      return $row;


    }


    /**
     * Returns sum of each extra type in one inning
     *
     * @param  int $gameId
     * @param  int $innings
     *
     * @return mixed
     */

    public function getExtras($gameId, $innings)
    {
        $teamId = $this->getTeamIdOfBattingTeam($gameId, $innings);

         $query = "SELECT SUM(BALLBYBALL_EXTR), BALLBYBALL_EXTRATYPE FROM BALLBYBALL
                   WHERE BALLBYBALL_EXTRATYPE != '0' AND BATSMAN_PLAYER_TEAM_GAME_GAME_ID = '$gameId' AND BATSMAN_PLAYER_TEAM_TEAM_ID = '$teamId'
                   GROUP BY BALLBYBALL_EXTRATYPE";

         //Correct version
//         $query = "SELECT SUM(BALLBYBALL_EXTR), BALLBYBALL_EXTRATYPE FROM BALLBYBALL
//                   WHERE BALLBYBALL_EXTRATYPE != '' AND BATSMAN_PLAYER_TEAM_GAME_GAME_ID = '$gameId' AND BATSMAN_PLAYER_TEAM_TEAM_ID = '$teamId'
//                   GROUP BY BALLBYBALL_EXTRATYPE";



                      $resultArray = array();
                      $this->_databaseAdapter->query($query);
                      while ($row = $this->_databaseAdapter->fetch()) {
                      extract($row);
                      $resultArray[]= $row;
                      }

                      $finalResult = array();
                      $counter = 0;
                      foreach ($resultArray as $key => $value) {

                          $finalResult[$counter]['total'] = $value['SUM(BALLBYBALL_EXTR)'];
                          $finalResult[$counter]['extra type'] = $value['BALLBYBALL_EXTRATYPE'];
                          $counter++;
                      }

                      return $finalResult;
    }

    /**
     * Returns fall of wickets information in one inning
     *
     * @param  int $gameId
     * @param  int $innings
     *
     * @return mixed
     */

                         public function getFallOfWickets($gameId, $innings) {


                         $teamId = $this->getTeamIdOfBattingTeam($gameId, $innings);

                     $query = "select pp.PLAYER_POOL_FNAME, pp.PLAYER_POOL_LNAME, pp.PLAYER_POOL_ID,
                               p.PLAYER_ID,
                               bb.BALLBYBALL_ID FROM BALLBYBALL AS bb
                               LEFT JOIN BATSMAN AS b ON bb.BATSMAN_BATSMAN_ID = b.BATSMAN_ID
                               LEFT JOIN PLAYER AS p ON b.PLAYER_PLAYER_ID = p.PLAYER_ID
                               LEFT JOIN PLAYER_POOL AS pp ON p.PLAYER_POOL_PLAYER_POOL_ID = pp.PLAYER_POOL_ID
                               WHERE bb.BALLBYBALL_DIS IS TRUE AND bb.BATSMAN_PLAYER_TEAM_TEAM_ID = '$teamId'";



                      $resultArray = array();
                      $this->_databaseAdapter->query($query);
                      while ($row = $this->_databaseAdapter->fetch()) {
                      extract($row);
                      $resultArray[]= $row;
                      }

                      $final = array();

                      foreach ($resultArray as $key => $value) {
                          $ballId = $value['BALLBYBALL_ID'];
                          $query = "SELECT SUM(bb.BALLBYBALL_RUNS) AS runs, SUM(bb.BALLBYBALL_DIS) AS dismissals FROM BALLBYBALL AS bb WHERE bb.BATSMAN_PLAYER_TEAM_GAME_GAME_ID = '$gameId' AND bb.BALLBYBALL_ID <= '$ballId' AND bb.BATSMAN_PLAYER_TEAM_TEAM_ID = '$teamId'";
                          $this->_databaseAdapter->query($query);
                          $row = $this->_databaseAdapter->fetch();
                          $resultArray2 = array();
                          extract($row);
                          $resultArray2[]= $row;
                          $final[$key]['runs'] = $resultArray2[0]['runs'];
                          $final[$key]['dismissals'] = $resultArray2[0]['dismissals'];
                          $final[$key]['first_name'] = $value['PLAYER_POOL_FNAME'];
                          $final[$key]['last_name'] = $value['PLAYER_POOL_LNAME'];
                          $final[$key]['player_pool_id'] = $value['PLAYER_POOL_ID'];
                          $final[$key]['player_id'] = $value['PLAYER_ID'];

                                       //Count number of extras
        $this->_databaseTable = 'BALLBYBALL';
        $query = "SELECT COUNT(*) AS count FROM $this->_databaseTable WHERE BALLBYBALL_EXTR IS TRUE AND BATSMAN_PLAYER_TEAM_GAME_GAME_ID = '$gameId' AND BALLBYBALL_ID <= '$ballId' AND BATSMAN_PLAYER_TEAM_TEAM_ID = '$teamId'";
        $this->_databaseAdapter->query($query);
        $result = $this->_databaseAdapter->fetch();
        $numberOfExtras = $result['count'];

        $query = "SELECT COUNT(*) AS count FROM $this->_databaseTable WHERE BATSMAN_PLAYER_TEAM_GAME_GAME_ID = '$gameId' AND BALLBYBALL_ID <= '$ballId'AND BATSMAN_PLAYER_TEAM_TEAM_ID = '$teamId'";
        $this->_databaseAdapter->query($query);
        $result = $this->_databaseAdapter->fetch();
        $numberOfTotalBalls = $result['count'];
        $numberOfBalls = $numberOfTotalBalls - $numberOfExtras;
        $over = $this->calculateOver($numberOfBalls);
          $final[$key]['over'] = $over;


                      }
                      return $final;


    }


           public function isGameFinished($gameID) {

                                       //Count number of extras
       $numberOfBalls1 = $this->getNumberOfBalls($gameID, '1');
       $numberOfBalls2 = $this->getNumberOfBalls($gameID, '2');
       $numberOfBalls = $numberOfBalls1 + $numberOfBalls2;

        if($numberOfBalls  >= 600 OR $this->getNumberOfDismissals($gameID) >= 20)
       //if($numberOfBalls  >= 120 OR $this->getNumberOfDismissals($gameID) >= 20)
        {
            return true;
        }
        else return false;
           }


           public function finaliseGameResult($gameId, $finalResult) {

        $this->_databaseTable = 'GAME';
        $gameData = array(
            'GAME_FINALRESLT' => $finalResult,
            'GAME_ACTIVE' => FALSE);
        $this->_databaseAdapter->update($this->_databaseTable, $gameData, "GAME_ID=$gameId");
        return true;
    }


    public function deleteBallByBall($gameId) {
        $query = "DELETE FROM BALLBYBALL WHERE BATSMAN_PLAYER_TEAM_GAME_GAME_ID = '$gameId'";
        $this->_databaseAdapter->query($query);
        $rows = $this->_databaseAdapter->getAffectedRows();
        if(empty($rows))
        {
            return false;
        } else {
            return true;
        }
    }

     /**
     * Returns data used to create Manhattan and Worm graphs
     *
     * @param  int $gameId
     * @param  int $innings
     *
     * @return mixed
     */

    public function getManhattanData($gameId, $innings)
    {
        //Get right team id
        $teamId = $this->getTeamIdOfBattingTeam($gameId, $innings);

        //Get runs and dismissals
        $query = "SELECT BALLBYBALL_RUNS, BALLBYBALL_DIS FROM BALLBYBALL WHERE BALLBYBALL_EXTR IS FALSE AND BATSMAN_PLAYER_TEAM_GAME_GAME_ID = '$gameId' AND BATSMAN_PLAYER_TEAM_TEAM_ID = '$teamId'";
        $resultArray = array();
        $this->_databaseAdapter->query($query);
        while ($row = $this->_databaseAdapter->fetch()) {
               extract($row);
                $resultArray[]= $row;
        }

        $manhattanData = array();

        //Initialise the counters
        $rowCounter = 0;
        $runs = 0;
        $wicketCounter = 0;
        $oversCounter = 0;

        //Get array size
        $arraySize = sizeof($resultArray);

        foreach ($resultArray as $key => $value) {

            ++$rowCounter;
            $runs = $runs + $resultArray[$key]['BALLBYBALL_RUNS'];
            if($resultArray[$key]['BALLBYBALL_DIS'] == TRUE)
            {
                ++$wicketCounter;
            }

            //Check that the over has ended if the game is finished
            if(($rowCounter == 6) OR ($key == ($arraySize - 1)))
            {
                ++$oversCounter;
                $manhattanData[$oversCounter]['runs'] = $runs;
                $manhattanData[$oversCounter]['wickets'] = $wicketCounter;
                $manhattanData[$oversCounter]['over'] = $oversCounter;

                //Reset the counters
                $wicketCounter = 0;
                $runs = 0;
                $rowCounter = 0;
            }

        }


        //return $resultArray;
        return $manhattanData;
        //return $oversCounter;
    }

    /**
     * Returns last ball id
     *
     * @param  int $gameId
     *
     * @return mixed
     */

    public function getLastBallId($gameId)
    {
        $query = "SELECT BALLBYBALL_ID FROM BALLBYBALL WHERE BATSMAN_PLAYER_TEAM_GAME_GAME_ID = '$gameId'
                  ORDER BY BALLBYBALL_ID DESC LIMIT 1";
        $this->_databaseAdapter->query($query);
        $lastBallId = $this->_databaseAdapter->fetch();
        return $lastBallId['BALLBYBALL_ID'];
    }

    public function getLastBallCommentary($gameId)
    {
        $lastBallId = $this->getLastBallId($gameId);

        $query = "SELECT BALLBYBALL_COMNT FROM BALLBYBALL WHERE BALLBYBALL_ID = '$lastBallId'";
        $this->_databaseAdapter->query($query);
        $lastBallCommentary = $this->_databaseAdapter->fetch();
        return $lastBallCommentary['BALLBYBALL_COMNT'];

    }
     /**
     * Returns data used to create bar graph
     *
     * @param  int $gameId
     * @param  int $innings
     *
     * @return mixed
     */

    public function getBarGraphData($gameId, $innings)
    {
        $barGraphData = array();
        $teamId = $this->getTeamIdOfBattingTeam($gameId, $innings);

        $query = "SELECT COUNT(*) AS ones FROM BALLBYBALL WHERE BALLBYBALL_RUNS = '1' AND BATSMAN_PLAYER_TEAM_GAME_GAME_ID = '$gameId' AND BATSMAN_PLAYER_TEAM_TEAM_ID = '$teamId'";
        $this->_databaseAdapter->query($query);
        $resultArray = $this->_databaseAdapter->fetch();
        $barGraphData['ones'] = $resultArray['ones'];

        //Get twos
        $query = "SELECT COUNT(*) AS twos FROM BALLBYBALL WHERE BALLBYBALL_RUNS = '2' AND BATSMAN_PLAYER_TEAM_GAME_GAME_ID = '$gameId' AND BATSMAN_PLAYER_TEAM_TEAM_ID = '$teamId'";
        $this->_databaseAdapter->query($query);
        $resultArray = $this->_databaseAdapter->fetch();
        $barGraphData['twos'] = $resultArray['twos'];

        //Get threes
        $query = "SELECT COUNT(*) AS threes FROM BALLBYBALL WHERE BALLBYBALL_RUNS = '3' AND BATSMAN_PLAYER_TEAM_GAME_GAME_ID = '$gameId' AND BATSMAN_PLAYER_TEAM_TEAM_ID = '$teamId'";
        $this->_databaseAdapter->query($query);
        $resultArray = $this->_databaseAdapter->fetch();
        $barGraphData['threes'] = $resultArray['threes'];

        //Get fours
        $query = "SELECT COUNT(*) AS fours FROM BALLBYBALL WHERE BALLBYBALL_RUNS = '4' AND BATSMAN_PLAYER_TEAM_GAME_GAME_ID = '$gameId' AND BATSMAN_PLAYER_TEAM_TEAM_ID = '$teamId'";
        $this->_databaseAdapter->query($query);
        $resultArray = $this->_databaseAdapter->fetch();
        $barGraphData['fours'] = $resultArray['fours'];

        //Get fives
        $query = "SELECT COUNT(*) AS fives FROM BALLBYBALL WHERE BALLBYBALL_RUNS = '5' AND BATSMAN_PLAYER_TEAM_GAME_GAME_ID = '$gameId' AND BATSMAN_PLAYER_TEAM_TEAM_ID = '$teamId'";
        $this->_databaseAdapter->query($query);
        $resultArray = $this->_databaseAdapter->fetch();
        $barGraphData['fives'] = $resultArray['fives'];

        //Get sixes
        $query = "SELECT COUNT(*) AS sixes FROM BALLBYBALL WHERE BALLBYBALL_RUNS = '6' AND BATSMAN_PLAYER_TEAM_GAME_GAME_ID = '$gameId' AND BATSMAN_PLAYER_TEAM_TEAM_ID = '$teamId'";
        $this->_databaseAdapter->query($query);
        $resultArray = $this->_databaseAdapter->fetch();
        $barGraphData['sixes'] = $resultArray['sixes'];

        return $barGraphData;
    }

     /**
     * Returns information of batsmen who still have to bat for a innings
     *
     * @param  int $gameId
     * @param  int $innings
     *
     * @return mixed
     */

    public function stillToBat($gameId, $innings)
    {
        $teamId = $this->getTeamIdOfBattingTeam($gameId, $innings);



                       $query = "SELECT p.PLAYER_ID
                                 FROM PLAYER AS p
                                 LEFT JOIN PLAYER_POOL AS pp ON p.PLAYER_POOL_PLAYER_POOL_ID = pp.PLAYER_POOL_ID
                                 WHERE p.TEAM_GAME_GAME_ID='$gameId' AND p.TEAM_TEAM_ID = '$teamId'
                                 ORDER BY p.PLAYER_BAT_ORDR ASC";

                       $actualBatsmanOrderArray = array();
                       $this->_databaseAdapter->query($query);
                        while ($row = $this->_databaseAdapter->fetch()) {
         extract($row);
         $actualBatsmanOrderArray[]= $row['PLAYER_ID'];
        }



                               $query = "SELECT BATSMAN_PLAYER_PLAYER_ID FROM BALLBYBALL WHERE BATSMAN_PLAYER_TEAM_GAME_GAME_ID = '$gameId' AND BATSMAN_PLAYER_TEAM_TEAM_ID = '$teamId'
                                   ORDER BY BALLBYBALL_ID ASC";

                       $dimissedBatsmanOrderArray = array();
                       $this->_databaseAdapter->query($query);
                        while ($row = $this->_databaseAdapter->fetch()) {
         extract($row);
         $dimissedBatsmanOrderArray[]= $row['BATSMAN_PLAYER_PLAYER_ID'];
        }

        $undismissedBatsmanArray = array_diff($actualBatsmanOrderArray, $dimissedBatsmanOrderArray);
        reset($undismissedBatsmanArray);

        $StillToBat = array();
        foreach ($undismissedBatsmanArray as $key => $value) {
            $batsmanId = $value;
            $query = "SELECT p.PLAYER_ID, pp.PLAYER_POOL_FNAME, pp.PLAYER_POOL_LNAME, p.TEAM_TEAM_ID
                                 FROM PLAYER AS p
                                 LEFT JOIN PLAYER_POOL AS pp ON p.PLAYER_POOL_PLAYER_POOL_ID = pp.PLAYER_POOL_ID
                                 WHERE p.TEAM_GAME_GAME_ID='$gameId' AND p.TEAM_TEAM_ID = '$teamId' AND p.PLAYER_ID = '$batsmanId'";
            $this->_databaseAdapter->query($query);
                          $row = $this->_databaseAdapter->fetch();
                          $resultArray2 = array();
                          extract($row);
                          $resultArray2[]= $row;
                          $StillToBat[$key]['player id'] = $resultArray2[0]['PLAYER_ID'];
                          $StillToBat[$key]['name'] = $resultArray2[0]['PLAYER_POOL_FNAME'];
                          $StillToBat[$key]['surname'] = $resultArray2[0]['PLAYER_POOL_LNAME'];


        }
        return $StillToBat;
    }

    /**
     * Returns run profile of current over
     *
     * @param  int $gameId
     *
     * @return mixed
     */

    public function getOverProfile($gameId)
    {
        //Get current innings
        $innings = $this->getInnings($gameId);

        //Get team Id of batting team
        $teamId = $this->getTeamIdOfBattingTeam($gameId, $innings);
        //Get runs and dismissals
        $query = "SELECT BALLBYBALL_RUNS, BALLBYBALL_EXTR, BALLBYBALL_EXTRATYPE FROM BALLBYBALL WHERE  BATSMAN_PLAYER_TEAM_GAME_GAME_ID = '$gameId' AND BATSMAN_PLAYER_TEAM_TEAM_ID = '$teamId'";
        $resultArray = array();
        $this->_databaseAdapter->query($query);
        while ($row = $this->_databaseAdapter->fetch()) {
               extract($row);
                $resultArray[]= $row;
        }

        $overProfileData = array();

        //Initialise the counters;
        $ballCounter = 0;
        $overCounter = 0;

        //Get array size
        $arraySize = sizeof($resultArray);

        foreach ($resultArray as $key => $value) {

            //Check that the over has ended
            if($ballCounter == 6)
            {
                //Reset the counters
                $ballCounter = 0;
                $overCounter++;
            }

            if($resultArray[$key]['BALLBYBALL_EXTR'] != TRUE)
            {
                $overProfileData[$overCounter][] = $resultArray[$key]['BALLBYBALL_RUNS'];
                ++$ballCounter;
            }
            else{
                $overProfileData[$overCounter][] = $resultArray[$key]['BALLBYBALL_EXTRATYPE'];
            }

            //Check that this is the last portion of the array
            if($key == ($arraySize - 1)){
                        $CurrentOverProfileData = array_pop($overProfileData);

        return $overProfileData;
            }

        }


    }

}

?>
